<template>
  <div class="dashboard-container">
    <div class="dashboard-header">
      <h1>欢迎回来，{{ userName }}</h1>
      <p class="dashboard-subtitle">今天是 {{ formatDate(today) }}</p>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="skeleton-container">
      <el-skeleton 
        v-for="n in skeletonCount" 
        :key="n"
        class="skeleton-item"
        height="200px"
      />
    </div>

    <!-- 教师信息卡片组 -->
    <div v-else-if="userRole === 'teacher' || userRole === 'admin'" class="card-container">
      <!-- 教师基本信息卡片 -->
      <el-card class="info-card" @click="handleCardClick('basic-info')">
        <div class="card-header">
          <el-icon class="card-icon"><User /></el-icon>
          <h3 class="card-title">个人基本信息</h3>
        </div>
        <div class="card-content">
          <div class="info-item">
            <span class="info-label">登录账号：</span>
            <span class="info-value">{{ teacherInfo?.username }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">姓名：</span>
            <span class="info-value">{{ teacherInfo?.name }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">职位：</span>
            <span class="info-value">{{ teacherInfo?.position }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">角色：</span>
            <span class="info-value">{{ teacherInfo?.role }}</span>
          </div>
        </div>
      </el-card>

      <!-- 负责班级卡片 -->
      <el-card class="info-card class-card" @click="handleCardClick('classes')">
        <div class="card-header">
          <el-icon class="card-icon"><School /></el-icon>
          <h3 class="card-title">负责班级</h3>
        </div>
        <div class="card-content">
          <el-table 
            :data="teacherInfo?.responsible_classes" 
            border 
            size="medium"
            :show-header="true"
            @row-click="handleClassClick"
          >
            <el-table-column prop="grade" label="年级" width="80">
              <template #default="scope">{{ scope.row.grade }}年级</template>
            </el-table-column>
            <el-table-column prop="class_name" label="班级" width="100" />
            <el-table-column prop="taught_subjects" label="任教课程">
              <template #default="scope">{{ scope.row.taught_subjects.join('、') }}</template>
            </el-table-column>
            <el-table-column label="班主任" width="80">
              <template #default="scope">
                <el-tag v-if="scope.row.is_head_teacher" type="success">是</el-tag>
                <el-tag v-else type="info">否</el-tag>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-card>

      <!-- 未读留言卡片 -->
      <el-card class="info-card" @click="handleCardClick('messages')">
        <div class="card-header">
          <el-icon class="card-icon"><Message /></el-icon>
          <h3 class="card-title">未读留言</h3>
        </div>
        <div class="card-content center-content">
          <div class="stat-value">{{ teacherInfo?.unread_message_count }}</div>
          <div class="stat-desc">条未读留言</div>
        </div>
      </el-card>
    </div>

    <!-- 学生信息卡片组 -->
    <div v-else-if="userRole === 'student'" class="card-container">
      <!-- 学生基本信息卡片 -->
      <el-card class="info-card" @click="handleCardClick('student-info')">
        <div class="card-header">
          <el-icon class="card-icon"><UserFilled /></el-icon>
          <h3 class="card-title">个人信息</h3>
        </div>
        <div class="card-content">
          <div class="info-item">
            <span class="info-label">登录账号：</span>
            <span class="info-value">{{ studentInfo?.username }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">姓名：</span>
            <span class="info-value">{{ studentInfo?.student_name }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">学号：</span>
            <span class="info-value">{{ studentInfo?.student_id }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">积分：</span>
            <span class="info-value">{{ studentInfo?.performance_points }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">班级排名：</span>
            <span class="info-value">{{ studentInfo?.class_rank }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">班级：</span>
            <span class="info-value">{{ studentInfo?.grade }}年级{{ studentInfo?.class_name }}</span>
          </div>
        </div>
      </el-card>

      <!-- 小组信息卡片 -->
      <el-card class="info-card" @click="handleCardClick('group')">
        <div class="card-header">
          <el-icon class="card-icon"><Flag /></el-icon>
          <h3 class="card-title">小组信息</h3>
        </div>
        <div class="card-content">
          <div class="info-item">
            <span class="info-label">小组名称：</span>
            <span class="info-value">{{ studentInfo?.group_name }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">小组积分：</span>
            <span class="info-value">{{ studentInfo?.group_total_points }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">小组排名：</span>
            <span class="info-value">{{ studentInfo?.group_rank }}</span>
          </div>
        </div>
      </el-card>

      <!-- 未完成考试卡片 -->
      <el-card class="info-card" @click="handleCardClick('pending-exams')">
        <div class="card-header">
          <el-icon class="card-icon"><Document /></el-icon>
          <h3 class="card-title">未完成考试</h3>
        </div>
        <div class="card-content center-content">
          <div class="stat-value">{{ studentInfo?.pending_exams_count }}</div>
          <div class="stat-desc">场未完成考试</div>
        </div>
      </el-card>

      <!-- 未读留言卡片 -->
      <el-card class="info-card" @click="handleCardClick('messages')">
        <div class="card-header">
          <el-icon class="card-icon"><Message /></el-icon>
          <h3 class="card-title">未读留言</h3>
        </div>
        <div class="card-content center-content">
          <div class="stat-value">{{ studentInfo?.unread_message_count }}</div>
          <div class="stat-desc">条未读留言</div>
        </div>
      </el-card>
    </div>

    <!-- 班级任课教师对话框 -->
    <el-dialog 
      v-model="classTeacherDialogVisible" 
      title="班级任课教师列表" 
      :width="600"
      @close="handleDialogClose"
    >
      <div class="dialog-header">
        <el-button type="primary" @click="handleAddTeacher">新增任课老师</el-button>
      </div>
      <el-table 
        :data="subjectTeachers" 
        border 
        size="small"
        style="width: 100%; margin-top: 10px"
      >
        <el-table-column prop="subject" label="课程名称" />
        <el-table-column prop="teacher_name" label="教师姓名" />
        <el-table-column label="操作">
          <template #default="scope">
            <el-button 
              type="text" 
              size="small" 
              @click="handleEditTeacher(scope.row)"
            >
              编辑
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <!-- 新增/编辑任课教师对话框 -->
    <el-dialog 
      v-model="editTeacherDialogVisible" 
      :title="isEditMode ? '编辑任课教师' : '新增任课教师'" 
      :width="500"
    >
      <el-form 
        :model="teacherForm" 
        ref="teacherFormRef"
        label-width="100px"
        style="margin-top: 20px"
      >
        <el-form-item 
          label="课程名称" 
          prop="subject"
          :rules="[{ required: true, message: '请输入课程名称', trigger: 'blur' }]"
        >
          <el-input 
            v-model="teacherForm.subject" 
            placeholder="请输入课程名称"
          />
        </el-form-item>
        <el-form-item 
          label="教师姓名" 
          prop="teacher_id"
          :rules="[{ required: true, message: '请选择教师', trigger: 'change' }]"
        >
          <el-select 
            v-model="teacherForm.teacher_id"
            placeholder="请选择教师"
            filterable
            remote
            :remote-method="handleTeacherSearch"
            :loading="teacherLoading"
          >
            <el-option 
              v-for="teacher in allTeachers" 
              :key="teacher.teacher_id" 
              :label="teacher.teacher_name" 
              :value="teacher.teacher_id"
            />
          </el-select>
        </el-form-item>
        <el-form-item 
          label="教师口令" 
          prop="admin_password"
          :rules="[{ required: true, message: '请输入教师口令', trigger: 'blur' }]"
        >
          <el-input 
            v-model="teacherForm.admin_password" 
            placeholder="请输入教师口令"
            type="password" 
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editTeacherDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSaveTeacher">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue';
//import { useRouter } from 'vue-router';
import { useAuthStore } from '../../store/authStore';
import { ElForm, ElMessage } from 'element-plus';
import { getTeacherInfo, getStudentInfo } from '../../api/user';
import type { TeacherInfoResponse, StudentInfoResponse } from '../../api/user';

// 引入图标
import { User, School, Message, UserFilled, Flag, Document } from '@element-plus/icons-vue';
import { listTeachers } from '../../api/teachermgr';
import { getSubjectTeacher, setSubjectTeacher } from '../../api/classmgr';
import { useRouter } from 'vue-router';

// 路由实例
const router = useRouter();
// 状态管理
const authStore = useAuthStore();
const userRole = computed(() => authStore.user?.role);
const userName = computed(() => {
  if (userRole.value === 'teacher' || userRole.value === 'admin') {
    return teacherInfo.value?.name || '';
  }
  return studentInfo.value?.student_name || '';
});

// 数据状态
const loading = ref(true);
const teacherInfo = ref<TeacherInfoResponse['content'] | null>(null);
const studentInfo = ref<StudentInfoResponse['content'] | null>(null);
const today = ref(new Date());
const skeletonCount = computed(() => userRole.value === 'student' ? 4 : 3);

// 班级教师相关状态
const classTeacherDialogVisible = ref(false);
const currentClassId = ref<number | null>(null);
const currentClassName = ref('');
const subjectTeachers = ref<any[]>([]); // 班级学科教师列表
const editTeacherDialogVisible = ref(false);
const isEditMode = ref(false);
const allTeachers = ref<any[]>([]); // 所有教师列表
const teacherLoading = ref(false);
const teacherForm = ref({
  subject: '',
  teacher_id: null,
  admin_password: ''
});
const teacherFormRef = ref<InstanceType<typeof ElForm>>();
const selectClassSubjectId = ref<number | null>(null);

// 日期格式化函数
const formatDate = (date: Date) => {
  return new Intl.DateTimeFormat('zh-CN', {
    year: 'numeric',
    month: 'long',
    day: 'numeric',
    weekday: 'long'
  }).format(date);
};

// 页面加载时获取数据
onMounted(async () => {
  try {
    loading.value = true;
    if (userRole.value === 'teacher' || userRole.value === 'admin') {
      const res = await getTeacherInfo();
      if (res.code === 200) {
        teacherInfo.value = res.content;
      } else {
        ElMessage.error(res.msg || '获取教师信息失败');
      }
    } else if (userRole.value === 'student') {
      const res = await getStudentInfo();
      if (res.code === 200) {
        studentInfo.value = res.content;
      } else {
        ElMessage.error(res.msg || '获取学生信息失败');
      }
    }
  } catch (error: any) {
    ElMessage.error(error.message || '获取信息异常');
  } finally {
    loading.value = false;
  }
});

// 卡片点击处理函数
const handleCardClick = (cardType: string) => {
  switch (cardType) {
    case 'student-info':
    case 'group':
      router.push('profile')
      break;
    case 'pending-exams':
      router.push('myexams')
      break;
    case 'messages':
      router.push('messages')
      break;
    default:
      break;
  }
};

// 点击某班级项
const handleClassClick = async (row: any) => {
  // 判断当前教师是否是该班班主任
  if (row.is_head_teacher) {
    currentClassId.value = row.class_id;
    currentClassName.value = `${row.grade}年级${row.class_name}`;
    try {
      const res = await getSubjectTeacher({ class_id: row.class_id });
      if (res.code === 200) {
        subjectTeachers.value = res.content || [];
        classTeacherDialogVisible.value = true;
      } else {
        ElMessage.error(res.msg || '获取班级教师信息失败');
      }
    } catch (error: any) {
      ElMessage.error(error.message || '获取班级教师信息异常');
    }
  } else {
    // 非班主任，显示提示信息
    ElMessage.info('您不是该班班主任，无法进行管理操作');
  }
};

// 关闭对话框时重置数据
const handleDialogClose = () => {
  subjectTeachers.value = [];
  currentClassId.value = null;
  currentClassName.value = '';
};

// 新增任课教师
const handleAddTeacher = async () => {
  // 初始化表单
  teacherForm.value = {
    subject: '',
    teacher_id: null,
    admin_password: ''
  };
  isEditMode.value = false;
  editTeacherDialogVisible.value = true;
  selectClassSubjectId.value = null;
};

// 编辑任课教师
const handleEditTeacher = async (row: any) => {
  // 填充表单数据
  teacherForm.value = {
    subject: row.subject,
    teacher_id: row.teacher_id ?? null,
    admin_password: row.admin_password
  };
  isEditMode.value = true;
  editTeacherDialogVisible.value = true;
  selectClassSubjectId.value = row.id;
};

// 加载所有教师列表
const loadAllTeachers = async (name?: string) => {
  try {
    teacherLoading.value = true;
    const res = await listTeachers({ name: name });
    if (res.code === 200) {
      allTeachers.value = res.content || [];
    } else {
      ElMessage.error(res.msg || '获取教师列表失败');
    }
  } catch (error: any) {
    ElMessage.error(error.message || '获取教师列表异常');
  } finally {
    teacherLoading.value = false;
  }
};

// 搜索教师
const handleTeacherSearch = (query: string) => {
  loadAllTeachers(query);
};

// 保存教师信息
const handleSaveTeacher = async () => {
  if (!teacherFormRef.value) return;
  
  // 表单验证
  await teacherFormRef.value.validate();
  
  if (!currentClassId.value) {
    ElMessage.error('班级信息异常');
    return;
  }
  
  try {
    var params = {
      class_id: currentClassId.value,
      subject: teacherForm.value.subject,
      teacher_id: teacherForm.value.teacher_id ?? 0,
      admin_password: teacherForm.value.admin_password
    };
    if (selectClassSubjectId.value != null) {
      Object.assign(params, { id: selectClassSubjectId.value });
    }
    
    const res = await setSubjectTeacher(params);
    if (res.code === 200) {
      ElMessage.success(isEditMode.value ? '编辑成功' : '新增成功');
      editTeacherDialogVisible.value = false;
      
      // 重新加载班级教师列表
      const refreshRes = await getSubjectTeacher({ class_id: currentClassId.value });
      if (refreshRes.code === 200) {
        subjectTeachers.value = refreshRes.content || [];
      }
    } else {
      ElMessage.error(res.msg || (isEditMode.value ? '编辑失败' : '新增失败'));
    }
  } catch (error: any) {
    ElMessage.error(error.message || '操作异常');
  }
};
</script>

<style scoped>
/* 页面容器背景与body一致 */
.dashboard-container {
  padding: 20px;
  min-height: calc(100vh - 60px); /* 减去顶部导航高度 */
}

.dashboard-header {
  margin-bottom: 30px;
  color: var(--text-primary);
}

.dashboard-header h1 {
  margin: 0 0 10px 0;
  font-size: 24px;
  font-weight: 600;
}

.dashboard-subtitle {
  margin: 0;
  color: var(--text-secondary);
  font-size: 14px;
}

/* 卡片容器：横向排列，自动换行 */
.card-container {
  display: flex;
  flex-wrap: wrap; /* 超出换行 */
  gap: 20px; /* 卡片间距 */
}

/* 卡片样式：与登录页卡片背景一致 */
.info-card {
  flex: 1; /* 自动分配宽度 */
  min-width: 300px; /* 最小宽度，确保内容不挤压 */
  background-color: #f0f2f5; /* 与LoginView卡片背景一致 */
  border: none;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  cursor: pointer;
  transition: all 0.3s ease;
  overflow: hidden;
}

/* 教师负责班级卡片宽度调整 */
.class-card {
  flex: 2;
  min-width: 500px;
}

.info-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.12);
}

.card-header {
  display: flex;
  align-items: center;
  padding: 15px 20px;
  border-bottom: 1px solid #e5e7eb;
}

.card-icon {
  font-size: 20px;
  color: #409eff;
  margin-right: 10px;
}

.card-title {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: var(--text-primary);
}

.card-content {
  padding: 20px;
}

/* 个人信息卡片：左对齐，增强label醒目度 */
.info-item {
  margin-bottom: 15px;
  font-size: 15px; /* 增大字体 */
  text-align: left; /* 强制左对齐 */
}

.info-item:last-child {
  margin-bottom: 0;
}

.info-label {
  color: #2d3748; /* 加深颜色 */
  font-weight: 600; /* 加粗 */
  display: inline-block;
  width: 90px; /* 加宽label区域 */
  margin-right: 10px;
}

.info-value {
  color: #4a5568;
  font-weight: 500;
}

.center-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 10px 0;
  min-height: 120px;
}

.stat-value {
  font-size: 36px;
  font-weight: 700;
  color: #409eff;
  margin-bottom: 10px;
}

.stat-desc {
  color: var(--text-secondary);
  font-size: 14px;
}

/* 加载骨架屏样式 */
.skeleton-container {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
}

.skeleton-item {
  flex: 1;
  min-width: 300px;
  border-radius: 12px;
}

/* 表格样式补充 */
::deep(.el-table th) {
  border-bottom: 2px solid #dee2e6 !important;
}

::deep(.el-table td) {
  border-bottom: 1px solid #e8f4f8 !important;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .class-card {
    min-width: 300px;
    flex: 1;
  }
  
  .info-card {
    min-width: 100%;
  }
  
  .info-label {
    width: 80px;
  }
}
</style>